package cn.kmsoft.stgeometry.util;

import cn.kmsoft.common.utils.DateUtil;
import cn.kmsoft.common.utils.FileUtil;
import cn.kmsoft.common.utils.StringUtil;
import cn.kmsoft.stgeometry.landm.Block;
import cn.kmsoft.stgeometry.landm.Land;
import cn.kmsoft.wololo.jts2geojson.GeoJSONReader;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vividsolutions.jts.geom.*;
import com.vividsolutions.jts.io.WKTReader;
import org.geotools.data.DataUtilities;
import org.geotools.data.FeatureWriter;
import org.geotools.data.Transaction;
import org.geotools.data.collection.ListFeatureCollection;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.geojson.geom.GeometryJSON;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.CRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.FactoryException;
import org.json.simple.JSONObject;

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 实现了GeoJson与Shp文件的相互转换，包括wkt与json、json数据内容保存为shp文件等
 */
public class GeoJson2Shapefile {
    private static GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);

    /**
     * @param args
     */
    public static void main(String[] args) {
        wktJsonConvertTest();
    }

    public static void test() {
//		try {
//			// 创建工作目录
//			String root = "F:\\Data\\shp\\test\\";
//			String workdir = UUID.randomUUID().toString();
//			File work = new File(root + workdir);
//			work.mkdir();
//
//			// 根据geojson生成shapefile
//			// String name = "重庆";
//			String name = "岛宗-fz";
//			// String jsonpath = "F:\\Data\\shp\\test\\a.geojson";
//			String jsonpath = "F:\\Data\\shp\\test\\岛宗-fz.geojson";
//			String json = FileUtil.readFile(new File(jsonpath));
//			String wkt = "PROJCS[\"Xian_1980_GK_Zone_18\",GEOGCS[\"GCS_Xian_1980\",DATUM[\"D_Xian_1980\",SPHEROID[\"Xian_1980\",6378140.0,298.257]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",18500000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",105.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]";
//			String geometryType = "esriGeometryPolygon";
//			// String fields =
//			// "[{\"name\":\"FID\",\"type\":\"esriFieldTypeOID\",\"alias\":\"FID\"},{\"name\":\"NAME\",\"type\":\"esriFieldTypeString\",\"alias\":\"NAME\"},{\"name\":\"CITY_CODE\",\"type\":\"esriFieldTypeString\",\"alias\":\"CITY_CODE\"},{\"name\":\"Name_PY\",\"type\":\"esriFieldTypeString\",\"alias\":\"Name_PY\"},{\"name\":\"COUNTY_COD\",\"type\":\"esriFieldTypeString\",\"alias\":\"COUNTY_COD\"},{\"name\":\"COUNTY_NAM\",\"type\":\"esriFieldTypeString\",\"alias\":\"COUNTY_NAM\"},{\"name\":\"CITY_NAME\",\"type\":\"esriFieldTypeString\",\"alias\":\"CITY_NAME\"},{\"name\":\"PROVINCE_C\",\"type\":\"esriFieldTypeString\",\"alias\":\"PROVINCE_C\"},{\"name\":\"PROVINCE_N\",\"type\":\"esriFieldTypeString\",\"alias\":\"PROVINCE_N\"},{\"name\":\"TYPE_CODE\",\"type\":\"esriFieldTypeString\",\"alias\":\"TYPE_CODE\"},{\"name\":\"Address\",\"type\":\"esriFieldTypeString\",\"alias\":\"Address\"},{\"name\":\"Name_ENG\",\"type\":\"esriFieldTypeString\",\"alias\":\"Name_ENG\"},{\"name\":\"Shape_Leng\",\"type\":\"esriFieldTypeDouble\",\"alias\":\"Shape_Leng\"},{\"name\":\"FID_chongqing_project_chongqing_project\",\"type\":\"esriFieldTypeInteger\",\"alias\":\"FID_chongqing_project_chongqing_project\"},{\"name\":\"name_1\",\"type\":\"esriFieldTypeString\",\"alias\":\"name_1\"},{\"name\":\"city_code_1\",\"type\":\"esriFieldTypeString\",\"alias\":\"city_code_1\"},{\"name\":\"name_py_1\",\"type\":\"esriFieldTypeString\",\"alias\":\"name_py_1\"},{\"name\":\"county_cod_1\",\"type\":\"esriFieldTypeString\",\"alias\":\"county_cod_1\"},{\"name\":\"county_nam_1\",\"type\":\"esriFieldTypeString\",\"alias\":\"county_nam_1\"},{\"name\":\"city_name_1\",\"type\":\"esriFieldTypeString\",\"alias\":\"city_name_1\"},{\"name\":\"province_c_1\",\"type\":\"esriFieldTypeString\",\"alias\":\"province_c_1\"},{\"name\":\"province_n_1\",\"type\":\"esriFieldTypeString\",\"alias\":\"province_n_1\"},{\"name\":\"type_code_1\",\"type\":\"esriFieldTypeString\",\"alias\":\"type_code_1\"},{\"name\":\"address_1\",\"type\":\"esriFieldTypeString\",\"alias\":\"address_1\"},{\"name\":\"name_eng_1\",\"type\":\"esriFieldTypeString\",\"alias\":\"name_eng_1\"},{\"name\":\"shape_leng_1\",\"type\":\"esriFieldTypeDouble\",\"alias\":\"shape_leng_1\"},{\"name\":\"Shape_Area\",\"type\":\"esriFieldTypeDouble\",\"alias\":\"Shape_Area\"}]";
//			String fields = "[{\"name\":\"name\",\"type\":\"esriFieldTypeString\",\"alias\":\"name\"},{\"name\":\"type\",\"type\":\"esriFieldTypeString\",\"alias\":\"type\"},{\"name\":\"bz\",\"type\":\"esriFieldTypeString\",\"alias\":\"bz\"}]";
//			createShapefile(root, workdir, name, json, wkt, geometryType.toLowerCase(), fields);
//
//			// 将shapefile压缩成zip文件
//			String[] exts = "dbf prj shp shx".split(" ");
//			zip(root, workdir, name, exts);
//
//			// 清除临时文件
//			// clear(root, workdir);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
    }

    public static void wktJsonConvertTest() {
        String inwkt = "POINT(114.298456 30.553544)";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "北清路");
        map.put("author", "李雷");

        String jsonStr = wkt2json(inwkt, map);
        System.out.println(jsonStr);

        String wkt = json2Wkt(jsonStr);
        System.out.println(wkt);

    }

    public static String wkt2json(String wkt, Map<String, Object> map) {
        String jsonStr = null;

        try {
            StringWriter writer = new StringWriter();

            WKTReader reader = new WKTReader();
            Geometry geometry = reader.read(wkt);
            GeometryJSON geo = new GeometryJSON();
            geo.write(geometry, writer);
            map.put("geometry", writer);

            jsonStr = JSONObject.toJSONString(map);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonStr;
    }

    public static String wkt2geojson(String wkt, String bz) {

        String geojson = null;
        String geoType = JTSGeometryWKTUtil.getGeoTypeFromWkt(wkt);

        try {
            SimpleFeatureType TYPE = null;
            //新建
            if ("polygon".equalsIgnoreCase(geoType)) {
                TYPE = DataUtilities.createType("Link", "geometry:Polygon,"+ // <- the geometry
                        "bz:String"); // <- a String attribute);

            } else if ("multipolygon".equalsIgnoreCase(geoType)) {
                TYPE = DataUtilities.createType("Link", "geometry:MultiPolygon,"+ // <- the geometry
                        "bz:String"); // <- a String attribute);
            }
            SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
            WKTReader reader = new WKTReader(geometryFactory);
            FeatureJSON fjson = new FeatureJSON();

            List<SimpleFeature> features = new ArrayList<>();
            SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, features);
            if("polygon".equalsIgnoreCase(geoType)) {
                //转换wkt为polygon
                Polygon polygon = (Polygon) reader.read(wkt);
                featureBuilder.add(polygon);//图形字段
            }else if("multipolygon".equalsIgnoreCase(geoType)) {
                //转换wkt为multipolygon
                MultiPolygon multipolygon = (MultiPolygon) reader.read(wkt);
                featureBuilder.add(multipolygon);//图形字段
            }
            featureBuilder.add(bz);//String类型的bz属性字段
            SimpleFeature feature = featureBuilder.buildFeature(null);
            features.add(feature);

            StringWriter writer = new StringWriter();
            fjson.writeFeatureCollection(collection, writer);

            // 导出geojson文件
            geojson = writer.toString();
        }catch(Exception ex) {
            ex.printStackTrace();
        }

        return geojson;
    }

    public static String json2Wkt(String gjsonStr) {
        String wkt = null;
        GeometryJSON gjson = new GeometryJSON();
        Reader reader = new StringReader(gjsonStr);
        try {
            Geometry geometry = gjson.read(reader);
            wkt = geometry.toText();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wkt;
    }

    /**
     * 一个txt文件转成一个shp文件，需要生成临时json
     *
     * @param shpfilePath  存放生成shp的路径
     * @param shpName      生成的shp的名
     * @param json
     * @param wkt
     * @param geometryType
     * @param fields
     * @throws IOException
     * @throws FactoryException
     */
    public static void createShapefile0(String shpfilePath, String shpName, String json, String wkt, String geometryType,
                                        String fields) throws IOException, FactoryException {
        // 创建shape文件对象
        File file = new File(shpfilePath + "\\" + shpName);
        System.out.println("shapefile-->: " + file.getAbsolutePath());

        String bz = shpName;
        // File file = new File(root + "\\" + name + ".shp");
        Map<String, Serializable> params = new HashMap<String, Serializable>();
        // params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
        params.put("url", file.toURI().toURL());
        ShapefileDataStore shpfileDataStore = (ShapefileDataStore) new ShapefileDataStoreFactory()
                .createNewDataStore(params);

        // 定义坐标系和字符集
        SimpleFeatureTypeBuilder simplefeaTypeBuilder = new SimpleFeatureTypeBuilder();
        // String wkt =
        // "PROJCS[\"Xian_1980_GK_Zone_18\",GEOGCS[\"GCS_Xian_1980\",DATUM[\"D_Xian_1980\",SPHEROID[\"Xian_1980\",6378140.0,298.257]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",18500000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",105.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]";
        simplefeaTypeBuilder.setCRS(CRS.parseWKT(wkt));
        // shpfileDataStore.setCharset(Charset.forName("utf-8"));
        shpfileDataStore.setCharset(Charset.forName("GBK"));
        simplefeaTypeBuilder.setName("shapefile");

        // 定义几何类型
        if (geometryType.endsWith("point")) {
            simplefeaTypeBuilder.add("the_geom", Point.class);
        } else if (geometryType.endsWith("line")) {
            simplefeaTypeBuilder.add("the_geom", LineString.class);
        } else {
            simplefeaTypeBuilder.add("the_geom", Polygon.class);
        }

        // 定义属性字段
        JsonNode fnode = new ObjectMapper().readTree(fields);
        Iterator<JsonNode> fieldsIter = fnode.iterator();
        while (fieldsIter.hasNext()) {
            JsonNode f = fieldsIter.next();
            String fn = f.get("name").toString().replaceAll("\"", "");
            String ft = f.get("type").toString().replaceAll("\"", "");

            if (ft.equalsIgnoreCase("esriFieldTypeOID") || ft.equalsIgnoreCase("esriFieldTypeInteger")) {
                simplefeaTypeBuilder.add(fn, Integer.class);
            } else if (ft.equalsIgnoreCase("esriFieldTypeDouble")) {
                simplefeaTypeBuilder.add(fn, Double.class);
            } else if (ft.equalsIgnoreCase("esriFieldTypeFloat")) {
                simplefeaTypeBuilder.add(fn, Float.class);
            } else {
                simplefeaTypeBuilder.add(fn, String.class);
            }
        }

        shpfileDataStore.createSchema(simplefeaTypeBuilder.buildFeatureType());

        // 解析geojson文件
        JsonNode node = new ObjectMapper().readTree(json);

        // 设置Reader和Writer
        GeoJSONReader reader = new GeoJSONReader();
        FeatureWriter<SimpleFeatureType, SimpleFeature> writer = shpfileDataStore
                .getFeatureWriter(shpfileDataStore.getTypeNames()[0], Transaction.AUTO_COMMIT);
        int max = 10; // shapefile字段名最长10个字节

        //lv add
        GeometryJSON gjson = new GeometryJSON(10);

        int indexOfFeature = 0;
        Iterator<JsonNode> featuresIter = node.get("features").iterator();
        while (featuresIter.hasNext()) {
            indexOfFeature++;
            System.out.println("---开始处理第 " + indexOfFeature + " 个图形要素");

            JsonNode feaNode = featuresIter.next();
            JsonNode attrNode = feaNode.get("properties");// 属性
//			org.locationtech.jts.geom.Geometry geometry = reader.read(feaNode.get("geometry").toString());// 图形
            Reader reader1 = new StringReader(feaNode.get("geometry").toString());
            SimpleFeature feature = writer.next();

            fieldsIter = fnode.iterator();
            while (fieldsIter.hasNext()) {
                JsonNode f = fieldsIter.next();
                String fn = f.get("name").toString().replaceAll("\"", "");// name
                String ft = f.get("type").toString().replaceAll("\"", "");// type
                String sliceName = fn;

                if (sliceName.length() > max) {
                    // sn = slice(sn, max, "utf-8");
                    sliceName = slice(sliceName, max, "GBK");
                }
                String value = attrNode.get(fn).toString().replaceAll("\"", "");

                if (ft.equalsIgnoreCase("esriFieldTypeOID") || ft.equalsIgnoreCase("esriFieldTypeInteger")) {
                    feature.setAttribute(sliceName, Integer.parseInt(value));
                } else if (ft.equalsIgnoreCase("esriFieldTypeDouble")) {
                    feature.setAttribute(sliceName, Double.parseDouble(value));
                } else if (ft.equalsIgnoreCase("esriFieldTypeFloat")) {
                    feature.setAttribute(sliceName, Float.parseFloat(value));
                } else if (ft.equalsIgnoreCase("esriFieldTypeString") && fn.equalsIgnoreCase("bz")) {
                    feature.setAttribute(sliceName, bz);
                } else {
                    feature.setAttribute(sliceName, value);
                }
            }
//			feature.setAttribute("the_geom", geometry);
            feature.setAttribute("the_geom", gjson.read(reader1));

        }

        writer.write();
        writer.close();

        shpfileDataStore.dispose();
    }

    /**
     * 一个txt文件转成一个shp文件，需要生成临时json
     *
     * @param root
     * @param name
     * @param json
     * @param wkt
     * @param geometryType
     * @param fields
     * @throws IOException
     * @throws FactoryException
     */
    public static void createShape(String root, String name, String json, String wkt, String geometryType, String fields) throws IOException, FactoryException {
        // 创建shape文件对象
        File file = new File(root + "\\" + name + ".shp");
        System.out.println("shapefile-->: " + file.getAbsolutePath());

        String bz = name;
        Map<String, Serializable> params = new HashMap<String, Serializable>();
        params.put("url", file.toURI().toURL());
        ShapefileDataStore shpfileDataStore = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);

        // 定义坐标系和字符集
        SimpleFeatureTypeBuilder simplefeaTypeBuilder = new SimpleFeatureTypeBuilder();

        simplefeaTypeBuilder.setCRS(CRS.parseWKT(wkt));
        //shpfileDataStore.setCharset(Charset.forName("utf-8"));
        shpfileDataStore.setCharset(Charset.forName("GBK"));
        simplefeaTypeBuilder.setName("shapefile");

        // 定义几何类型
        if (geometryType.endsWith("point")) {
            simplefeaTypeBuilder.add("the_geom", Point.class);
        } else if (geometryType.endsWith("line")) {
            simplefeaTypeBuilder.add("the_geom", LineString.class);
        } else {
            simplefeaTypeBuilder.add("the_geom", Polygon.class);
        }

        // 定义属性字段
        JsonNode fnode = new ObjectMapper().readTree(fields);
        Iterator<JsonNode> fieldsIter = fnode.iterator();
        while (fieldsIter.hasNext()) {
            JsonNode f = fieldsIter.next();
            String fn = f.get("name").toString().replaceAll("\"", "");
            String ft = f.get("type").toString().replaceAll("\"", "");

            if (ft.equalsIgnoreCase("esriFieldTypeOID") || ft.equalsIgnoreCase("esriFieldTypeInteger")) {
                simplefeaTypeBuilder.add(fn, Integer.class);
            } else if (ft.equalsIgnoreCase("esriFieldTypeDouble")) {
                simplefeaTypeBuilder.add(fn, Double.class);
            } else if (ft.equalsIgnoreCase("esriFieldTypeFloat")) {
                simplefeaTypeBuilder.add(fn, Float.class);
            } else {
                simplefeaTypeBuilder.add(fn, String.class);
            }
        }

        shpfileDataStore.createSchema(simplefeaTypeBuilder.buildFeatureType());

        // 解析geojson文件
        JsonNode node = new ObjectMapper().readTree(json);

        // 设置Reader和Writer
//		GeoJSONReader reader = new GeoJSONReader();
        FeatureWriter<SimpleFeatureType, SimpleFeature> writer = shpfileDataStore.getFeatureWriter(
                shpfileDataStore.getTypeNames()[0],
                Transaction.AUTO_COMMIT);
        int max = 10;    // shapefile字段名最长10个字节

        //lv add
        GeometryJSON gjson = new GeometryJSON(10);

        int indexOfFeature = 0;
        Iterator<JsonNode> featuresIter = node.get("features").iterator();
        while (featuresIter.hasNext()) {
            indexOfFeature++;
            System.out.println("---开始处理第 " + indexOfFeature + " 个图形要素");

            JsonNode feaNode = featuresIter.next();
            JsonNode attrNode = feaNode.get("properties");//属性
//            org.locationtech.jts.geom.Geometry geometry = reader.read(feaNode.get("geometry").toString());//图形
            Reader reader = new StringReader(feaNode.get("geometry").toString());
            SimpleFeature feature = writer.next();

            fieldsIter = fnode.iterator();
            while (fieldsIter.hasNext()) {
                JsonNode f = fieldsIter.next();
                String fn = f.get("name").toString().replaceAll("\"", "");//name
                String ft = f.get("type").toString().replaceAll("\"", "");//type
                String sliceName = fn;

                if (sliceName.length() > max) {
                    //sn = slice(sn, max, "utf-8");
                    sliceName = slice(sliceName, max, "GBK");
                }
                String value = attrNode.get(fn).toString().replaceAll("\"", "");

                if (ft.equalsIgnoreCase("esriFieldTypeOID") || ft.equalsIgnoreCase("esriFieldTypeInteger")) {
                    feature.setAttribute(sliceName, Integer.parseInt(value));
                } else if (ft.equalsIgnoreCase("esriFieldTypeDouble")) {
                    feature.setAttribute(sliceName, Double.parseDouble(value));
                } else if (ft.equalsIgnoreCase("esriFieldTypeFloat")) {
                    feature.setAttribute(sliceName, Float.parseFloat(value));
                } else if (ft.equalsIgnoreCase("esriFieldTypeString") && fn.equalsIgnoreCase("bz")) {
                    feature.setAttribute(sliceName, bz);
                } else {
                    feature.setAttribute(sliceName, value);
                }
            }
//            feature.setAttribute("the_geom", geometry);
            feature.setAttribute("the_geom", gjson.read(reader));
        }

        writer.write();
        writer.close();

        shpfileDataStore.dispose();
    }

    /**
     * 一个txt文件转成一个shp文件，需要生成临时json
     *
     * @param root
     * @param workdir
     * @param name
     * @param json
     * @param crs_wkt
     * @param geometryType
     * @param fields
     * @throws IOException
     * @throws FactoryException
     */
    public static void createShapefile(String root, String workdir, String name, String json, String crs_wkt, String geometryType, String fields) throws IOException, FactoryException {
        // 创建shape文件对象
        File file = new File(root + workdir + "\\" + name + ".shp");
        System.out.println("shapefile-->: " + file.getAbsolutePath());

        String bz = name;
        //File file = new File(root + "\\" + name + ".shp");
        Map<String, Serializable> params = new HashMap<String, Serializable>();
        //params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
        params.put("url", file.toURI().toURL());
        ShapefileDataStore shpfileDataStore = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);

        // 定义坐标系和字符集
        SimpleFeatureTypeBuilder simplefeaTypeBuilder = new SimpleFeatureTypeBuilder();

        //String wkt = "PROJCS[\"Xian_1980_GK_Zone_18\",GEOGCS[\"GCS_Xian_1980\",DATUM[\"D_Xian_1980\",SPHEROID[\"Xian_1980\",6378140.0,298.257]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",18500000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",105.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]";
        simplefeaTypeBuilder.setCRS(CRS.parseWKT(crs_wkt));
        //shpfileDataStore.setCharset(Charset.forName("utf-8"));
        shpfileDataStore.setCharset(Charset.forName("GBK"));
        simplefeaTypeBuilder.setName("shapefile");

        // 定义几何类型
        if (geometryType.endsWith("point")) {
            simplefeaTypeBuilder.add("the_geom", Point.class);
        } else if (geometryType.endsWith("line")) {
            simplefeaTypeBuilder.add("the_geom", LineString.class);
        } else {
            simplefeaTypeBuilder.add("the_geom", Polygon.class);
        }

        // 定义属性字段
        JsonNode fnode = new ObjectMapper().readTree(fields);
        Iterator<JsonNode> fieldsIter = fnode.iterator();
        while (fieldsIter.hasNext()) {
            JsonNode f = fieldsIter.next();
            String fn = f.get("name").toString().replaceAll("\"", "");
            String ft = f.get("type").toString().replaceAll("\"", "");

            if (ft.equalsIgnoreCase("esriFieldTypeOID") || ft.equalsIgnoreCase("esriFieldTypeInteger")) {
                simplefeaTypeBuilder.add(fn, Integer.class);
            } else if (ft.equalsIgnoreCase("esriFieldTypeDouble")) {
                simplefeaTypeBuilder.add(fn, Double.class);
            } else if (ft.equalsIgnoreCase("esriFieldTypeFloat")) {
                simplefeaTypeBuilder.add(fn, Float.class);
            } else {
                simplefeaTypeBuilder.add(fn, String.class);
            }
        }

        shpfileDataStore.createSchema(simplefeaTypeBuilder.buildFeatureType());

        // 解析geojson文件
        JsonNode node = new ObjectMapper().readTree(json);

        // 设置Reader和Writer
        GeoJSONReader reader = new GeoJSONReader();
        FeatureWriter<SimpleFeatureType, SimpleFeature> writer = shpfileDataStore.getFeatureWriter(
                shpfileDataStore.getTypeNames()[0],
                Transaction.AUTO_COMMIT);
        int max = 10;    // shapefile字段名最长10个字节

        //lv add
        GeometryJSON gjson = new GeometryJSON(10);

        int indexOfFeature = 0;
        Iterator<JsonNode> featuresIter = node.get("features").iterator();
        while (featuresIter.hasNext()) {
            indexOfFeature++;
            System.out.println("---开始处理第 " + indexOfFeature + " 个图形要素");

            JsonNode feaNode = featuresIter.next();
            JsonNode attrNode = feaNode.get("properties");//属性
//            org.locationtech.jts.geom.Geometry geometry = reader.read(feaNode.get("geometry").toString());//图形
            Reader reader1 = new StringReader(feaNode.get("geometry").toString());
            SimpleFeature feature = writer.next();

            fieldsIter = fnode.iterator();
            while (fieldsIter.hasNext()) {
                JsonNode f = fieldsIter.next();
                String fn = f.get("name").toString().replaceAll("\"", "");//name
                String ft = f.get("type").toString().replaceAll("\"", "");//type
                String sliceName = fn;

                if (sliceName.length() > max) {
                    //sn = slice(sn, max, "utf-8");
                    sliceName = slice(sliceName, max, "GBK");
                }
                String value = attrNode.get(fn).toString().replaceAll("\"", "");

                if (ft.equalsIgnoreCase("esriFieldTypeOID") || ft.equalsIgnoreCase("esriFieldTypeInteger")) {
                    feature.setAttribute(sliceName, Integer.parseInt(value));
                } else if (ft.equalsIgnoreCase("esriFieldTypeDouble")) {
                    feature.setAttribute(sliceName, Double.parseDouble(value));
                } else if (ft.equalsIgnoreCase("esriFieldTypeFloat")) {
                    feature.setAttribute(sliceName, Float.parseFloat(value));
                } else if (ft.equalsIgnoreCase("esriFieldTypeString") && fn.equalsIgnoreCase("bz")) {
                    feature.setAttribute(sliceName, bz);
                } else {
                    feature.setAttribute(sliceName, value);
                }
            }
//            feature.setAttribute("the_geom", geometry);
            feature.setAttribute("the_geom", gjson.read(reader1));
        }

        writer.write();
        writer.close();

        shpfileDataStore.dispose();
    }

    public static void createShapefile1(File file, String json, String crs_wkt, String geometryType, String fields) throws IOException, FactoryException {
        // 创建shape文件对象

        //File file = new File(root + "\\" + name + ".shp");
        Map<String, Serializable> params = new HashMap<String, Serializable>();
        //params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
        params.put("url", file.toURI().toURL());
        ShapefileDataStore shpfileDataStore = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);

        // 定义坐标系和字符集
        SimpleFeatureTypeBuilder simplefeaTypeBuilder = new SimpleFeatureTypeBuilder();

        //String crs_wkt = "PROJCS[\"Xian_1980_GK_Zone_18\",GEOGCS[\"GCS_Xian_1980\",DATUM[\"D_Xian_1980\",SPHEROID[\"Xian_1980\",6378140.0,298.257]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",18500000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",105.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]";
        simplefeaTypeBuilder.setCRS(CRS.parseWKT(crs_wkt));
        //shpfileDataStore.setCharset(Charset.forName("utf-8"));
        shpfileDataStore.setCharset(Charset.forName("GBK"));
        simplefeaTypeBuilder.setName("shapefile");

        // 定义几何类型
        if (geometryType.endsWith("point")) {
            simplefeaTypeBuilder.add("the_geom", Point.class);
        } else if (geometryType.endsWith("line")) {
            simplefeaTypeBuilder.add("the_geom", LineString.class);
        } else {
            simplefeaTypeBuilder.add("the_geom", Polygon.class);
        }

        // 定义属性字段
        JsonNode fnode = new ObjectMapper().readTree(fields);
        Iterator<JsonNode> fieldsIter = fnode.iterator();
        while (fieldsIter.hasNext()) {
            JsonNode f = fieldsIter.next();
            String fn = f.get("name").toString().replaceAll("\"", "");
            String ft = f.get("type").toString().replaceAll("\"", "");

            if (ft.equalsIgnoreCase("esriFieldTypeOID") || ft.equalsIgnoreCase("esriFieldTypeInteger")) {
                simplefeaTypeBuilder.add(fn, Integer.class);
            } else if (ft.equalsIgnoreCase("esriFieldTypeDouble")) {
                simplefeaTypeBuilder.add(fn, Double.class);
            } else if (ft.equalsIgnoreCase("esriFieldTypeFloat")) {
                simplefeaTypeBuilder.add(fn, Float.class);
            } else {
                simplefeaTypeBuilder.add(fn, String.class);
            }
        }

        shpfileDataStore.createSchema(simplefeaTypeBuilder.buildFeatureType());

        // 解析geojson文件
        JsonNode node = new ObjectMapper().readTree(json);
        // 设置Reader和Writer
        GeoJSONReader reader = new GeoJSONReader();
        FeatureWriter<SimpleFeatureType, SimpleFeature> writer = shpfileDataStore.getFeatureWriter(
                shpfileDataStore.getTypeNames()[0],
                Transaction.AUTO_COMMIT);
        int max = 10;    // shapefile字段名最长10个字节

        //lv add
        GeometryJSON gjson = new GeometryJSON(10);

        int indexOfFeature = 0;
        Iterator<JsonNode> featuresIter = node.get("features").iterator();
        while (featuresIter.hasNext()) {
            indexOfFeature++;
            System.out.println("---开始处理第 " + indexOfFeature + " 个图形要素");

            JsonNode feaNode = featuresIter.next();
            JsonNode attrNode = feaNode.get("properties");//属性
            //org.locationtech.jts.geom.Geometry geometry = reader.read(feaNode.get("geometry").toString());//图形
            Reader reader1 = new StringReader(feaNode.get("geometry").toString());
            SimpleFeature feature = writer.next();

            fieldsIter = fnode.iterator();
            while (fieldsIter.hasNext()) {
                JsonNode f = fieldsIter.next();
                String fn = f.get("name").toString().replaceAll("\"", "");//name
                String ft = f.get("type").toString().replaceAll("\"", "");//type
                String sliceName = fn;

                if (sliceName.length() > max) {
                    //sn = slice(sn, max, "utf-8");
                    sliceName = slice(sliceName, max, "GBK");
                }
                JsonNode jsonNode = attrNode.get(fn);
                String value="";
                if(jsonNode != null) {
                    value = jsonNode.toString().replaceAll("\"", "");
                }

                if (ft.equalsIgnoreCase("esriFieldTypeOID") || ft.equalsIgnoreCase("esriFieldTypeInteger")) {
                    feature.setAttribute(sliceName, Integer.parseInt(value));
                } else if (ft.equalsIgnoreCase("esriFieldTypeDouble")) {
                    feature.setAttribute(sliceName, Double.parseDouble(value));
                } else if (ft.equalsIgnoreCase("esriFieldTypeFloat")) {
                    feature.setAttribute(sliceName, Float.parseFloat(value));
                } else if (ft.equalsIgnoreCase("esriFieldTypeString") && fn.equalsIgnoreCase("bz")) {
                    feature.setAttribute(sliceName, "");
                } else {
                    feature.setAttribute(sliceName, value);
                }
            }
//            feature.setAttribute("the_geom", geometry);
            feature.setAttribute("the_geom", gjson.read(reader1));
        }

        writer.write();
        writer.close();

        shpfileDataStore.dispose();
    }

    /**
     * @param outfile
     * @param dzjghJsonMap
     * @param crs_wkt
     * @param geometryType
     * @param fields
     * @throws FactoryException
     * @throws JsonProcessingException
     * @throws IOException
     */
    public static void createShapefile2(File outfile, Map<String, String> dzjghJsonMap, String crs_wkt, String geometryType, String fields) throws FactoryException, JsonProcessingException, IOException {

        Map<String, Serializable> params = new HashMap<String, Serializable>();
        params.put("url", outfile.toURI().toURL());
        ShapefileDataStore shpfileDataStore = (ShapefileDataStore) new ShapefileDataStoreFactory()
                .createNewDataStore(params);

        // 定义坐标系和字符集
        SimpleFeatureTypeBuilder simplefeaTypeBuilder = new SimpleFeatureTypeBuilder();
        simplefeaTypeBuilder.setCRS(CRS.parseWKT(crs_wkt));
        // shpfileDataStore.setCharset(Charset.forName("utf-8"));
        shpfileDataStore.setCharset(Charset.forName("GBK"));
        simplefeaTypeBuilder.setName("shapefile");
        // 定义几何类型
        if (geometryType.endsWith("point")) {
            simplefeaTypeBuilder.add("the_geom", Point.class);
        } else if (geometryType.endsWith("line")) {
            simplefeaTypeBuilder.add("the_geom", LineString.class);
        } else {
            simplefeaTypeBuilder.add("the_geom", Polygon.class);
        }

        // 定义属性字段
        System.out.println(String.format("--->定义属性字段 "));
        JsonNode fnode = new ObjectMapper().readTree(fields);
        Iterator<JsonNode> fieldsIter = fnode.iterator();
        while (fieldsIter.hasNext()) {
            JsonNode f = fieldsIter.next();
            String fn = f.get("name").toString().replaceAll("\"", "");
            String ft = f.get("type").toString().replaceAll("\"", "");

            if (ft.equalsIgnoreCase("esriFieldTypeOID") || ft.equalsIgnoreCase("esriFieldTypeInteger")) {
                simplefeaTypeBuilder.add(fn, Integer.class);
            } else if (ft.equalsIgnoreCase("esriFieldTypeDouble")) {
                simplefeaTypeBuilder.add(fn, Double.class);
            } else if (ft.equalsIgnoreCase("esriFieldTypeFloat")) {
                simplefeaTypeBuilder.add(fn, Float.class);
            } else {
                simplefeaTypeBuilder.add(fn, String.class);
            }
        }

        shpfileDataStore.createSchema(simplefeaTypeBuilder.buildFeatureType());

        // 设置Reader和Writer
        GeoJSONReader reader = new GeoJSONReader();
        FeatureWriter<SimpleFeatureType, SimpleFeature> writer = null;
        try {
            writer = shpfileDataStore.getFeatureWriter(
                    shpfileDataStore.getTypeNames()[0], Transaction.AUTO_COMMIT);

        } catch (IOException e1) {
            e1.printStackTrace();
        }

        int max = 10;    // shapefile字段名最长10个字节

        ObjectMapper hhh = new ObjectMapper();
        //逐个txt文件访问
        Set<String> dzjghSet = dzjghJsonMap.keySet();
        Iterator<String> dzjghIter = dzjghSet.iterator();
        int dzjghNum = 0;
        File file = null;
        while (dzjghIter.hasNext()) {
            dzjghNum++;
            //电子监管号
            String dzjgh = dzjghIter.next();
            String bz = dzjgh;

            String jsonfilePath = dzjghJsonMap.get(dzjgh);
            file = new File(jsonfilePath);
            String jsonStr = "";
            try {
                jsonStr = FileUtil.readFile(file.getAbsoluteFile());
                if (dzjghNum >= 100) {
                    System.out.println("---test");
                }
                System.out.println();
                System.out.println(String.format("--->开始处理第  %d 个文件，电子监管号：%s ", dzjghNum, dzjgh));
                //解析geojson文件
                JsonNode node = hhh.readTree(jsonStr);
                //JsonNode node = new ObjectMapper().readTree(jsonStr);
                int indexOfFeature = 0;
                //遍历一个txt文件下包含多个feature图形
                Iterator<JsonNode> featuresIter = node.get("features").iterator();
                while (featuresIter.hasNext()) {
                    indexOfFeature++;
                    System.out.println("---处理第 " + indexOfFeature + " 个图形要素");

                    try {
                        JsonNode feaNode = featuresIter.next();
                        //属性信息
                        JsonNode attrNode = feaNode.get("properties");
                        Geometry geometry = reader.read(feaNode.get("geometry").toString());//图形
                        SimpleFeature feature = writer.next();
                        fieldsIter = fnode.iterator();
                        while (fieldsIter.hasNext()) {
                            JsonNode f = fieldsIter.next();
                            String fn = f.get("name").toString().replaceAll("\"", "");//name
                            String ft = f.get("type").toString().replaceAll("\"", "");//type
                            String sliceName = fn;

                            if (sliceName.length() > max) {
                                //sn = slice(sn, max, "utf-8");
                                sliceName = slice(sliceName, max, "GBK");
                            }
                            String value = attrNode.get(fn).toString().replaceAll("\"", "");

                            if (ft.equalsIgnoreCase("esriFieldTypeOID") || ft.equalsIgnoreCase("esriFieldTypeInteger")) {
                                feature.setAttribute(sliceName, Integer.parseInt(value));
                            } else if (ft.equalsIgnoreCase("esriFieldTypeDouble")) {
                                feature.setAttribute(sliceName, Double.parseDouble(value));
                            } else if (ft.equalsIgnoreCase("esriFieldTypeFloat")) {
                                feature.setAttribute(sliceName, Float.parseFloat(value));
                            } else if (ft.equalsIgnoreCase("esriFieldTypeString") && fn.equalsIgnoreCase("bz")) {
                                feature.setAttribute(sliceName, bz);
                            } else {
                                feature.setAttribute(sliceName, value);
                            }
                        }

                        feature.setAttribute("the_geom", geometry);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }

                writer.write();
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        writer.close();
        shpfileDataStore.dispose();
    }
    public static void createShapefile21(File outfile, Map<String, String> dzjghJsonStrMap, String crs_wkt, String geometryType, String fields) throws FactoryException, JsonProcessingException, IOException {

        Map<String, Serializable> params = new HashMap<String, Serializable>();
        params.put("url", outfile.toURI().toURL());
        ShapefileDataStore shpfileDataStore = (ShapefileDataStore) new ShapefileDataStoreFactory()
                .createNewDataStore(params);

        // 定义坐标系和字符集
        SimpleFeatureTypeBuilder simplefeaTypeBuilder = new SimpleFeatureTypeBuilder();
        simplefeaTypeBuilder.setCRS(CRS.parseWKT(crs_wkt));
        // shpfileDataStore.setCharset(Charset.forName("utf-8"));
        shpfileDataStore.setCharset(Charset.forName("GBK"));
        simplefeaTypeBuilder.setName("shapefile");
        // 定义几何类型
        if (geometryType.endsWith("point")) {
            simplefeaTypeBuilder.add("the_geom", Point.class);
        } else if (geometryType.endsWith("line")) {
            simplefeaTypeBuilder.add("the_geom", LineString.class);
        } else {
            simplefeaTypeBuilder.add("the_geom", Polygon.class);
        }

        // 定义属性字段
        System.out.println(String.format("--->定义属性字段 "));
        JsonNode fnode = new ObjectMapper().readTree(fields);
        Iterator<JsonNode> fieldsIter = fnode.iterator();
        while (fieldsIter.hasNext()) {
            JsonNode f = fieldsIter.next();
            String fn = f.get("name").toString().replaceAll("\"", "");
            String ft = f.get("type").toString().replaceAll("\"", "");

            if (ft.equalsIgnoreCase("esriFieldTypeOID") || ft.equalsIgnoreCase("esriFieldTypeInteger")) {
                simplefeaTypeBuilder.add(fn, Integer.class);
            } else if (ft.equalsIgnoreCase("esriFieldTypeDouble")) {
                simplefeaTypeBuilder.add(fn, Double.class);
            } else if (ft.equalsIgnoreCase("esriFieldTypeFloat")) {
                simplefeaTypeBuilder.add(fn, Float.class);
            } else {
                simplefeaTypeBuilder.add(fn, String.class);
            }
        }

        shpfileDataStore.createSchema(simplefeaTypeBuilder.buildFeatureType());

        // 设置Reader和Writer
        GeoJSONReader reader = new GeoJSONReader();
        FeatureWriter<SimpleFeatureType, SimpleFeature> writer = null;
        try {
            writer = shpfileDataStore.getFeatureWriter(
                    shpfileDataStore.getTypeNames()[0], Transaction.AUTO_COMMIT);

        } catch (IOException e1) {
            e1.printStackTrace();
        }

        int max = 10;    // shapefile字段名最长10个字节

        ObjectMapper hhh = new ObjectMapper();
        //逐个txt文件访问
        Set<String> dzjghSet = dzjghJsonStrMap.keySet();
        Iterator<String> dzjghIter = dzjghSet.iterator();
        int dzjghNum = 0;
        File file = null;
        while (dzjghIter.hasNext()) {
            dzjghNum++;

            System.out.println();
            //电子监管号
            String dzjgh = dzjghIter.next();
            String bz = dzjgh;

            try {
                //图形geojson
                String geojsonStr = dzjghJsonStrMap.get(dzjgh);
                //如果geojson为空则跳过
                if(StringUtil.isNullOrEmpty(geojsonStr) ) {

                    System.out.println(String.format("--->第  %d 个文件处理失败，geojson为空，电子监管号：%s ", dzjghNum, dzjgh));
                    continue;
                }

                System.out.println(String.format("--->开始处理第  %d 个文件，电子监管号：%s ", dzjghNum, dzjgh));
                //System.out.println(geojsonStr);

                //解析geojson文件
                JsonNode node = hhh.readTree(geojsonStr);
                //JsonNode node = new ObjectMapper().readTree(jsonStr);
                int indexOfFeature = 0;
                //遍历一个txt文件下包含多个feature图形
                Iterator<JsonNode> featuresIter = node.get("features").iterator();
                while (featuresIter.hasNext()) {
                    indexOfFeature++;
                    System.out.println("---处理第 " + indexOfFeature + " 个图形要素");

                    try {
                        JsonNode feaNode = featuresIter.next();
                        //属性信息
                        JsonNode attrNode = feaNode.get("properties");
                        Geometry geometry = reader.read(feaNode.get("geometry").toString());//图形
                        SimpleFeature feature = writer.next();
                        fieldsIter = fnode.iterator();
                        while (fieldsIter.hasNext()) {
                            JsonNode f = fieldsIter.next();
                            String fn = f.get("name").toString().replaceAll("\"", "");//name
                            String ft = f.get("type").toString().replaceAll("\"", "");//type
                            String sliceName = fn;

                            if (sliceName.length() > max) {
                                //sn = slice(sn, max, "utf-8");
                                sliceName = slice(sliceName, max, "GBK");
                            }
                            String value = attrNode.get(fn).toString().replaceAll("\"", "");

                            if (ft.equalsIgnoreCase("esriFieldTypeOID") || ft.equalsIgnoreCase("esriFieldTypeInteger")) {
                                feature.setAttribute(sliceName, Integer.parseInt(value));
                            } else if (ft.equalsIgnoreCase("esriFieldTypeDouble")) {
                                feature.setAttribute(sliceName, Double.parseDouble(value));
                            } else if (ft.equalsIgnoreCase("esriFieldTypeFloat")) {
                                feature.setAttribute(sliceName, Float.parseFloat(value));
                            } else if (ft.equalsIgnoreCase("esriFieldTypeString") && fn.equalsIgnoreCase("bz")) {
                                feature.setAttribute(sliceName, bz);
                            } else {
                                feature.setAttribute(sliceName, value);
                            }
                        }

                        feature.setAttribute("the_geom", geometry);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }

                writer.write();
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        writer.close();
        shpfileDataStore.dispose();
    }

    /**
     * createShapefile3-使用Land对象模型，将多个txt成果批量导入到一个shp文件中
     *
     * @param outfile
     * @param dzjghLandMap
     * @param crs_wkt
     * @param geometryType
     * @param fields
     * @return
     * @throws FactoryException
     * @throws JsonProcessingException
     * @throws IOException
     */
    public static Map<String, Set<String>> createShapefile3(File outfile,
                                                            Map<String, Land> dzjghLandMap,
                                                            String crs_wkt, String geometryType, String fields) throws FactoryException, JsonProcessingException, IOException {
        Map<String, Set<String>> res = new HashMap<String, Set<String>>();
        Set<String> successSet = new HashSet<String>();
        Set<String> failSet = new HashSet<String>();

        Map<String, Serializable> params = new HashMap<String, Serializable>();
        params.put("url", outfile.toURI().toURL());
        ShapefileDataStore shpfileDataStore = (ShapefileDataStore) new ShapefileDataStoreFactory()
                .createNewDataStore(params);

        // 定义坐标系和字符集
        SimpleFeatureTypeBuilder simplefeaTypeBuilder = new SimpleFeatureTypeBuilder();
        simplefeaTypeBuilder.setCRS(CRS.parseWKT(crs_wkt));
        shpfileDataStore.setCharset(Charset.forName("utf-8"));
        //shpfileDataStore.setCharset(Charset.forName("GBK"));
        simplefeaTypeBuilder.setName("shapefile");
        // 定义几何类型
        if (geometryType.endsWith("point")) {
            simplefeaTypeBuilder.add("the_geom", Point.class);
        } else if (geometryType.endsWith("line")) {
            simplefeaTypeBuilder.add("the_geom", LineString.class);
        } else {
            simplefeaTypeBuilder.add("the_geom", Polygon.class);
        }

        // 定义属性字段
        JsonNode fnode = new ObjectMapper().readTree(fields);
        Iterator<JsonNode> fieldsIter = fnode.iterator();
        while (fieldsIter.hasNext()) {
            JsonNode f = fieldsIter.next();
            String fn = f.get("name").toString().replaceAll("\"", "");
            String ft = f.get("type").toString().replaceAll("\"", "");

            if (ft.equalsIgnoreCase("esriFieldTypeOID") || ft.equalsIgnoreCase("esriFieldTypeInteger")) {
                simplefeaTypeBuilder.add(fn, Integer.class);
            } else if (ft.equalsIgnoreCase("esriFieldTypeDouble")) {
                simplefeaTypeBuilder.add(fn, Double.class);
            } else if (ft.equalsIgnoreCase("esriFieldTypeFloat")) {
                simplefeaTypeBuilder.add(fn, Float.class);
            } else {
                simplefeaTypeBuilder.add(fn, String.class);
            }
        }

        shpfileDataStore.createSchema(simplefeaTypeBuilder.buildFeatureType());

        // 设置Reader和Writer
        GeoJSONReader reader = new GeoJSONReader();
        FeatureWriter<SimpleFeatureType, SimpleFeature> writer = null;
        try {
            writer = shpfileDataStore.getFeatureWriter(
                    shpfileDataStore.getTypeNames()[0], Transaction.AUTO_COMMIT);

        } catch (IOException e1) {
            e1.printStackTrace();
        }

        int max = 10;    // shapefile字段名最长10个字节
        //逐个txt文件访问
        Set<String> dzjghSet = dzjghLandMap.keySet();
        int dzjghsSize = dzjghSet.size();
        Iterator<String> dzjghIter = dzjghSet.iterator();
        int dzjghNum = 0;
        while (dzjghIter.hasNext()) {
            dzjghNum++;
            //电子监管号
            String dzjgh = dzjghIter.next();
            String bz = dzjgh;

            Land land = dzjghLandMap.get(dzjgh);

            try {
                System.out.println();
                System.out.println(String.format("--->开始处理第  %d/%d 个文件，电子监管号：%s ", dzjghNum, dzjghsSize, dzjgh));

                ObjectMapper hhh = new ObjectMapper();

                //遍历一个txt文件下包含多个feature图形
                List<Block> blocks = land.getBlocks();//对应features
                int blocksSize = blocks.size();
                int indexOfBlock = 0;
                int sumOfSuccess = 0;
                System.out.println(String.format("--->一共有%d 个图形要素. ", blocksSize));
                Iterator<Block> blocksIter = blocks.iterator();
                while (blocksIter.hasNext()) {
                    indexOfBlock++;

                    System.out.println(String.format("---处理第 %d 个图形要素. ", indexOfBlock));
                    Block block = blocksIter.next();
                    //属性信息
                    Map<String, Object> bAttrs = block.getbAttrs();
                    //geojson
                    String json = block.toJsonStr();

                    try {
                        //com.alibaba.fastjson.JSONObject hh = JSON.parseObject(json);
                        SimpleFeature feature = writer.next();
                        JsonNode blockNode = hhh.readTree(json);
                        Geometry geometry = reader.read(blockNode.get("geometry").toString());//图形

                        fieldsIter = fnode.iterator();
                        while (fieldsIter.hasNext()) {
                            JsonNode f = fieldsIter.next();
                            String fn = f.get("name").toString().replaceAll("\"", "");//name
                            String ft = f.get("type").toString().replaceAll("\"", "");//type
                            String sliceName = fn;

                            if (sliceName.length() > max) {
                                sliceName = slice(sliceName, max, "GBK");
                            }
                            String value = "";
                            //String value = attrNode.get(fn).toString().replaceAll("\"", "");

                            if (ft.equalsIgnoreCase("esriFieldTypeOID") || ft.equalsIgnoreCase("esriFieldTypeInteger")) {
                                feature.setAttribute(sliceName, Integer.parseInt(value));
                            } else if (ft.equalsIgnoreCase("esriFieldTypeDouble") && fn.equalsIgnoreCase("dkmj")) {
                                double dkmj = block.getDkmj();
                                feature.setAttribute(sliceName, dkmj);
                            } else if (ft.equalsIgnoreCase("esriFieldTypeDouble")) {
                                feature.setAttribute(sliceName, Double.parseDouble(value));
                            } else if (ft.equalsIgnoreCase("esriFieldTypeFloat")) {
                                feature.setAttribute(sliceName, Float.parseFloat(value));

                            } else if (ft.equalsIgnoreCase("esriFieldTypeString") && fn.equalsIgnoreCase("pzwh")) {
                                feature.setAttribute(sliceName, dzjgh);
                            } else if (ft.equalsIgnoreCase("esriFieldTypeString") && fn.equalsIgnoreCase("dzjgh")) {
                                feature.setAttribute(sliceName, dzjgh);
                            } else if (ft.equalsIgnoreCase("esriFieldTypeString") && fn.equalsIgnoreCase("cbpwh")) {
                                feature.setAttribute(sliceName, dzjgh);
                            } else if (ft.equalsIgnoreCase("esriFieldTypeString") && fn.equalsIgnoreCase("bz")) {
                                feature.setAttribute(sliceName, bz);
                            } else {
                                feature.setAttribute(sliceName, value);
                            }
                        }
                        feature.setAttribute("the_geom", geometry);
                        System.out.println(String.format("---处理第 %s 个图形要素成功!", indexOfBlock));
                        //成功计数
                        sumOfSuccess++;
                    } catch (Exception ex) {
                        System.out.println(String.format("---处理第 %s 个图形要素失败!, 原因概述：%s", indexOfBlock, ex.getMessage()));
                        ex.printStackTrace();
                    }
                }
                writer.write();
                //要求所有地块处理之后
                if (sumOfSuccess == blocksSize) {
                    successSet.add(dzjgh);
                } else {
                    failSet.add(dzjgh);
                }
            } catch (JsonProcessingException e) {
                failSet.add(dzjgh);
                System.out.println(String.format("--->开始处理第  %d 个文件，电子监管号：%s 处理失败!", dzjghNum, dzjgh));
                e.printStackTrace();
            } catch (IOException e) {
                failSet.add(dzjgh);
                System.out.println(String.format("--->开始处理第  %d 个文件，电子监管号：%s 处理失败!", dzjghNum, dzjgh));
                e.printStackTrace();
            } finally {

            }
        }
        writer.close();
        shpfileDataStore.dispose();

        res.put("success", successSet);
        res.put("fail", failSet);

        return res;
    }


    /**
     * createShapefile4-使用Land对象模型，将多个txt成果批量导入到一个shp文件中
     * tip注意： 添加了36500000与36000000的坐标识别
     *
     * @param outfile
     * @param dzjghLandMap
     * @param crs_wkt
     * @param geometryType
     * @param fields
     * @return
     * @throws FactoryException
     * @throws JsonProcessingException
     * @throws IOException
     */
    public static Map<String, Set<String>> createShapefile4(File outfile, Map<String, Land> dzjghLandMap,
                                                            String crs_wkt, String geometryType, String fields) throws FactoryException, JsonProcessingException, IOException {
        Map<String, Set<String>> res = new HashMap<String, Set<String>>();
        Set<String> successSet = new HashSet<String>();
        Set<String> failSet = new HashSet<String>();

        Map<String, Serializable> params = new HashMap<String, Serializable>();
        params.put("url", outfile.toURI().toURL());
        ShapefileDataStore shpfileDataStore = (ShapefileDataStore) new ShapefileDataStoreFactory()
                .createNewDataStore(params);

        // 定义坐标系和字符集
        SimpleFeatureTypeBuilder simplefeaTypeBuilder = new SimpleFeatureTypeBuilder();
        simplefeaTypeBuilder.setCRS(CRS.parseWKT(crs_wkt));
        // shpfileDataStore.setCharset(Charset.forName("utf-8"));
        shpfileDataStore.setCharset(Charset.forName("GBK"));
        simplefeaTypeBuilder.setName("shapefile");
        // 定义几何类型
        if (geometryType.endsWith("point")) {
            simplefeaTypeBuilder.add("the_geom", Point.class);
        } else if (geometryType.endsWith("line")) {
            simplefeaTypeBuilder.add("the_geom", LineString.class);
        } else {
            simplefeaTypeBuilder.add("the_geom", Polygon.class);
        }

        // 定义属性字段
        JsonNode fnode = new ObjectMapper().readTree(fields);
        Iterator<JsonNode> fieldsIter = fnode.iterator();
        while (fieldsIter.hasNext()) {
            JsonNode f = fieldsIter.next();
            String fn = f.get("name").toString().replaceAll("\"", "");
            String ft = f.get("type").toString().replaceAll("\"", "");

            if (ft.equalsIgnoreCase("esriFieldTypeOID") || ft.equalsIgnoreCase("esriFieldTypeInteger")) {
                simplefeaTypeBuilder.add(fn, Integer.class);
            } else if (ft.equalsIgnoreCase("esriFieldTypeDouble")) {
                simplefeaTypeBuilder.add(fn, Double.class);
            } else if (ft.equalsIgnoreCase("esriFieldTypeFloat")) {
                simplefeaTypeBuilder.add(fn, Float.class);
            } else {
                simplefeaTypeBuilder.add(fn, String.class);
            }
        }

        shpfileDataStore.createSchema(simplefeaTypeBuilder.buildFeatureType());

        // 设置Reader和Writer
        GeoJSONReader reader = new GeoJSONReader();
        FeatureWriter<SimpleFeatureType, SimpleFeature> writer = null;
        try {
            writer = shpfileDataStore.getFeatureWriter(
                    shpfileDataStore.getTypeNames()[0], Transaction.AUTO_COMMIT);

        } catch (IOException e1) {
            e1.printStackTrace();
        }

        int max = 10;    // shapefile字段名最长10个字节

        //逐个txt文件访问
        Set<String> dzjghSet = dzjghLandMap.keySet();
        int dzjghsSize = dzjghSet.size();
        Iterator<String> dzjghIter = dzjghSet.iterator();
        int dzjghNum = 0;
        while (dzjghIter.hasNext()) {
            dzjghNum++;
            //电子监管号
            String dzjgh = dzjghIter.next();
            String bz = dzjgh;

            Land land = dzjghLandMap.get(dzjgh);

            try {
                System.out.println();
                System.out.println(String.format("--->开始处理第  %d/%d 个文件，电子监管号：%s ", dzjghNum, dzjghsSize, dzjgh));

                ObjectMapper hhh = new ObjectMapper();
                int indexOfFeature = 0;
                //遍历一个txt文件下包含多个feature图形
                List<Block> blocks = land.getBlocks();//对应features
                int featuresSize = blocks.size();
                System.out.println(String.format("--->一共有%d 个图形要素. ", featuresSize));
                Iterator<Block> featuresIter = blocks.iterator();
                while (featuresIter.hasNext()) {
                    indexOfFeature++;

                    System.out.println(String.format("---处理第 %d 个图形要素. ", indexOfFeature));
                    try {
                        Block block = featuresIter.next();
                        //属性信息
                        Map<String, Object> bAttrs = block.getbAttrs();
                        String dkmc = block.getDkmc();
                        //geojson
                        String json = block.toJsonStr();
                        //com.alibaba.fastjson.JSONObject hh = JSON.parseObject(json);
                        JsonNode blockNode = hhh.readTree(json);
                        Geometry geometry = reader.read(blockNode.get("geometry").toString());//图形

                        SimpleFeature feature = writer.next();
                        fieldsIter = fnode.iterator();
                        while (fieldsIter.hasNext()) {
                            JsonNode f = fieldsIter.next();
                            String fn = f.get("name").toString().replaceAll("\"", "");//name
                            String ft = f.get("type").toString().replaceAll("\"", "");//type
                            String sliceName = fn;

                            if (sliceName.length() > max) {
                                sliceName = slice(sliceName, max, "GBK");
                            }
                            String value = "";
                            //String value = attrNode.get(fn).toString().replaceAll("\"", "");

                            if (ft.equalsIgnoreCase("esriFieldTypeOID") || ft.equalsIgnoreCase("esriFieldTypeInteger")) {
                                feature.setAttribute(sliceName, Integer.parseInt(value));
                            } else if (ft.equalsIgnoreCase("esriFieldTypeDouble")) {
                                feature.setAttribute(sliceName, Double.parseDouble(value));
                            } else if (ft.equalsIgnoreCase("esriFieldTypeFloat")) {
                                feature.setAttribute(sliceName, Float.parseFloat(value));
                            } else if (ft.equalsIgnoreCase("esriFieldTypeString") && fn.equalsIgnoreCase("bz")) {
                                feature.setAttribute(sliceName, bz);
                            } else {
                                feature.setAttribute(sliceName, value);
                            }
                        }
                        feature.setAttribute("the_geom", geometry);
                        System.out.println(String.format("---处理第 %s 个图形要素成功!", indexOfFeature));
                    } catch (Exception ex) {
                        failSet.add(dzjgh);
                        System.out.println(String.format("---处理第 %s 个图形要素失败!, 原因概述：%s", indexOfFeature, ex.getMessage()));
                        //ex.printStackTrace();
                    }
                }
                writer.write();

                successSet.add(dzjgh);
            } catch (JsonProcessingException e) {
                failSet.add(dzjgh);
                System.out.println(String.format("--->开始处理第  %d 个文件，电子监管号：%s 处理失败!", dzjghNum, dzjgh));
                e.printStackTrace();
            } catch (IOException e) {
                failSet.add(dzjgh);
                System.out.println(String.format("--->开始处理第  %d 个文件，电子监管号：%s 处理失败!", dzjghNum, dzjgh));
                e.printStackTrace();
            }
        }
        writer.close();
        shpfileDataStore.dispose();

        res.put("success", successSet);
        res.put("fail", failSet);

        return res;
    }


    public static void createShapefile5(String shpPath, com.alibaba.fastjson.JSONObject geoJson,
                                        String crs_wkt, String encoding) throws FactoryException, JsonProcessingException, IOException {
        if (StringUtil.isNullOrEmpty(encoding)) {
            encoding = "GBK";
        }

        JSONArray features = (JSONArray) geoJson.get("features");
        com.alibaba.fastjson.JSONObject feature0 = features.getJSONObject(0);
        String strType = ((com.alibaba.fastjson.JSONObject) feature0.get("geometry")).getString("type").toString();

        Class<?> geoType = null;
        switch (strType) {
            case "Point":
                geoType = Point.class;
                break;
            case "MultiPoint":
                geoType = MultiPoint.class;
                break;
            case "LineString":
                geoType = LineString.class;
                break;
            case "MultiLineString":
                geoType = MultiLineString.class;
                break;
            case "Polygon":
                geoType = Polygon.class;
                break;
            case "MultiPolygon":
                geoType = MultiPolygon.class;
                break;
        }
        // 创建shape文件对象
        File file = new File(shpPath);
        Map<String, Serializable> params = new HashMap<String, Serializable>();
        params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
        ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);

        // 设置编码
        Charset charset = Charset.forName(encoding);
        ds.setCharset(charset);

        SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
        //坐标系与投影
        tb.setCRS(CRS.parseWKT(crs_wkt));
        //tb.setCRS(DefaultGeographicCRS.WGS84);
        tb.setName("shapefile");

        com.alibaba.fastjson.JSONObject properties = feature0.getJSONObject("properties");
        Map<String, String> map = new HashMap<String, String>();
        int index = 1;
        //构建字段结构
        if (properties != null) {
            Iterator<Entry<String, Object>> iterator = properties.entrySet().iterator();
            for (; iterator.hasNext(); ) {
                Entry<String, Object> entry = iterator.next();
                String key = entry.getKey();
                Object entValue = entry.getValue();
                Class<? extends Object> entType;
                //null
                if (StringUtil.isNullOrEmpty(entValue)) {
                    entType = String.class;
                } else {
                    entType = entValue.getClass();
                }

                tb.add(key, entType);
                map.put(key, key);
            }
        }

        tb.add("the_geom", geoType);
        // 定义图形信息和属性信息
        ds.createSchema(tb.buildFeatureType());


        GeometryJSON gjson = new GeometryJSON(10);
        // 设置Writer
        FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
        for (int i = 0, len = features.size(); i < len; i++) {
            // String strFeature = features.get(i).toString();
            com.alibaba.fastjson.JSONObject featureJson = features.getJSONObject(i);
            SimpleFeature feature = writer.next();
            com.alibaba.fastjson.JSONObject currProperties = featureJson.getJSONObject("properties");
            if (currProperties != null) {
                Iterator<Entry<String, Object>> iterator = currProperties.entrySet().iterator();
                for (; iterator.hasNext(); ) {
                    Entry<String, Object> entry = iterator.next();
                    Object val = entry.getValue();
                    if (val != null) {
                        String currKey = map.get(entry.getKey());
                        if (val instanceof String) {
                            if (StringUtil.isContainChinese((String) val)) {
                                feature.setAttribute(currKey, new String(val.toString()));
                            } else {
                                feature.setAttribute(currKey, val);
                            }
                        } else {
                            feature.setAttribute(currKey, val);
                        }
                    }
                }
            }

            String geometry = featureJson.getJSONObject("geometry").toString();
            Reader reader = new StringReader(geometry);
            feature.setAttribute("the_geom", gjson.read(reader));
            writer.write();
        }
        writer.close();
        ds.dispose();
    }


    public static void zip(String path, String workdir, String name, String[] exts) throws IOException {

        FileOutputStream zfos = new FileOutputStream(path + workdir + "\\" + name + ".zip");
        // FileOutputStream zfos = new FileOutputStream(path+ "\\" + + name + ".zip");
        /*
         * ArchiveOutputStream aos = new
         * ArchiveStreamFactory().createArchiveOutputStream("zip", zfos);
         * ZipArchiveOutputStream zaos = (ZipArchiveOutputStream)aos;
         * zaos.setEncoding("gbk"); // 防止中文名称乱码 BufferedInputStream bis = null; int
         * count; int BUFFER = 2048; byte data[] = new byte[BUFFER];
         *
         * for (int i = 0; i < exts.length; i++) { File file = new File(path +
         * "\\" + workdir + "\\" + name + "." + exts[i]); ZipArchiveEntry entry = new
         * ZipArchiveEntry(file, name + "." + exts[i]); zaos.putArchiveEntry(entry);
         * FileInputStream fis = new FileInputStream(file); bis = new
         * BufferedInputStream(fis, BUFFER);
         *
         * while((count = bis.read(data, 0, BUFFER)) != -1) { zaos.write(data, 0,
         * count); } bis.close(); zaos.closeArchiveEntry(); } zaos.flush();
         * zaos.finish();
         */

        ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(zfos));
        BufferedInputStream bis = null;
        int count;
        int BUFFER = 2048;
        byte data[] = new byte[BUFFER];

        for (int i = 0; i < exts.length; i++) {
            ZipEntry entry = new ZipEntry("data." + exts[i]);
            zos.putNextEntry(entry);
            FileInputStream fis = new FileInputStream(path + "\\" + workdir + "\\" + name + "." + exts[i]);
            bis = new BufferedInputStream(fis, BUFFER);

            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                zos.write(data, 0, count);
            }
            bis.close();
        }
        zos.close();
    }

    private static void clear(String root, String workdir) {
        File dir = new File(root + workdir);

        if (dir.exists()) {
            File[] files = dir.listFiles();

            for (int i = 0; i < files.length; i++) {
                files[i].delete();
            }
            dir.delete();
        }
    }

    private static String slice(String s, int max, String code) {
        String[] ss = s.split("");
        StringBuilder sb = new StringBuilder();
        int len = 0;

        for (int i = 0; i < ss.length; i++) {
            byte[] bytes = ss[i].getBytes(Charset.forName(code));
            len += bytes.length;

            if (len <= max) {
                sb.append(ss[i]);
            } else {
                break;
            }
        }
        return sb.toString();
    }

    /**
     * geoJson2ShpZip,返回shp的压缩文件存储的相关信息
     *
     * @param rootPath
     * @param wkid
     * @param geoJson
     * @param encoding
     * @return
     * @throws Exception
     */
    public static Map<String, String> geoJson2ShpZip(String rootPath, String wkid, com.alibaba.fastjson.JSONObject geoJson, String encoding) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String tmpOutDir = FileUtil.createTmpDir(rootPath);

        //转geojson到shp
        String shpFile = tmpOutDir + "/" + UUID.randomUUID().toString() + ".shp";
        geoJson2Shp(wkid, geoJson, shpFile, encoding);

        //压缩zip
        String yearMonth = DateUtil.getYearMonth();
        String realPath = rootPath + File.separator + yearMonth;
        FileUtil.creatFileDir(realPath);
        String fileName = "TMP_" + UUID.randomUUID().toString() + ".zip";
        String zipFile = realPath + "/" + fileName;
        FileUtil.toZip(tmpOutDir, zipFile, false);

        map.put("localUri", yearMonth + "/" + fileName);
        map.put("ext", "zip");
        map.put("fileName", fileName);
        return map;
    }


    /**
     * <b>描述:</b>json2shp,返回shp文件存储的相关信息 <br/>
     * <br/>
     *
     * @param geoJson
     * @return
     * @throws Exception
     */
    public static Map<String, String> geoJson2Shp(String rootPath, String wkid, com.alibaba.fastjson.JSONObject geoJson) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String yearMonth = DateUtil.getYearMonth();
        String realPath = rootPath + DateUtil.getYearMonth();

        FileUtil.creatFileDir(realPath);
        String fileName = UUID.randomUUID().toString() + ".shp";
        String shpFile = realPath + "/" + fileName;

        geoJson2Shp(wkid, geoJson, shpFile);

        map.put("localUri", yearMonth + "/" + fileName);
        map.put("ext", "shp");
        map.put("fileName", fileName);
        return map;
    }

    /**
     * GeoJSON 转换为shp，字符编码格式为GBK
     *
     * @param wkid    投影坐标系wkid
     * @param geoJson GeoJSON
     * @param shpFile shp路径
     * @throws Exception
     */
    public static void geoJson2Shp(String wkid, com.alibaba.fastjson.JSONObject geoJson, String shpFile) throws Exception {

        JSONArray features = (JSONArray) geoJson.get("features");
        com.alibaba.fastjson.JSONObject feature0 = features.getJSONObject(0);
        String strType = ((com.alibaba.fastjson.JSONObject) feature0.get("geometry")).getString("type").toString();

        Class<?> geoType = null;
        switch (strType) {
            case "Point":
                geoType = Point.class;
                break;
            case "MultiPoint":
                geoType = MultiPoint.class;
                break;
            case "LineString":
                geoType = LineString.class;
                break;
            case "MultiLineString":
                geoType = MultiLineString.class;
                break;
            case "Polygon":
                geoType = Polygon.class;
                break;
            case "MultiPolygon":
                geoType = MultiPolygon.class;
                break;
        }
        // 创建shape文件对象
        File file = new File(shpFile);
        Map<String, Serializable> params = new HashMap<String, Serializable>();
        params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
        ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);

        // 设置编码
        Charset charset = Charset.forName("GBK");
        ds.setCharset(charset);

        SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
        //坐标系与投影
        String wkt = CrsUtil.getWKT(wkid);
        tb.setCRS(CRS.parseWKT(wkt));
        //tb.setCRS(DefaultGeographicCRS.WGS84);
        tb.setName("shapefile");

        com.alibaba.fastjson.JSONObject properties = feature0.getJSONObject("properties");
        Map<String, String> map = new HashMap<String, String>();
        int index = 1;
        //构建字段结构
        if (properties != null) {
            Iterator<Entry<String, Object>> iterator = properties.entrySet().iterator();
            for (; iterator.hasNext(); ) {
                Entry<String, Object> entry = iterator.next();
                String key = entry.getKey();
                Object entValue = entry.getValue();
                Class<? extends Object> entType;
                //null
                if (StringUtil.isNullOrEmpty(entValue)) {
                    entType = String.class;
                } else {
                    entType = entValue.getClass();
                }
                //校验是否包含中文
                if (StringUtil.isContainChinese(key)) {
                    String currKey = "ZW" + index;
                    tb.add(currKey, entType);
                    map.put(key, currKey);
                    index++;
                } else {
                    tb.add(key, entType);
                    map.put(key, key);
                }
            }
        }
        tb.add("the_geom", geoType);
        // 定义图形信息和属性信息
        ds.createSchema(tb.buildFeatureType());

        GeometryJSON gjson = new GeometryJSON(10);
        // 设置Writer
        FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
        for (int i = 0, len = features.size(); i < len; i++) {
            // String strFeature = features.get(i).toString();
            com.alibaba.fastjson.JSONObject featureJson = features.getJSONObject(i);
            SimpleFeature feature = writer.next();
            com.alibaba.fastjson.JSONObject currProperties = featureJson.getJSONObject("properties");
            if (currProperties != null) {
                Iterator<Entry<String, Object>> iterator = currProperties.entrySet().iterator();
                for (; iterator.hasNext(); ) {
                    Entry<String, Object> entry = iterator.next();
                    Object val = entry.getValue();
                    if (val != null) {
                        String currKey = map.get(entry.getKey());
                        if (val instanceof String) {
                            if (StringUtil.isContainChinese((String) val)) {
                                feature.setAttribute(currKey, new String(val.toString().getBytes(), "GBK"));
                            } else {
                                feature.setAttribute(currKey, val);
                            }
                        } else {
                            feature.setAttribute(currKey, val);
                        }
                    }
                }
            }

            String geometry = featureJson.getJSONObject("geometry").toString();
            Reader reader = new StringReader(geometry);
            feature.setAttribute("the_geom", gjson.read(reader));
            writer.write();
        }
        writer.close();
        ds.dispose();
    }

    /**
     * GeoJSON 转换为shp
     *
     * @param wkid     投影坐标系wkid
     * @param geoJson  GeoJSON
     * @param shpFile  shp路径
     * @param encoding 字符编码
     * @throws Exception
     */
    public static void geoJson2Shp(String wkid, com.alibaba.fastjson.JSONObject geoJson, String shpFile, String encoding) throws Exception {
        if (StringUtil.isNullOrEmpty(encoding)) {
            encoding = "GBK";
        }
        JSONArray features = (JSONArray) geoJson.get("features");
        com.alibaba.fastjson.JSONObject feature0 = features.getJSONObject(0);
        String strType = ((com.alibaba.fastjson.JSONObject) feature0.get("geometry")).getString("type").toString();

        Class<?> geoType = null;
        switch (strType) {
            case "Point":
                geoType = Point.class;
                break;
            case "MultiPoint":
                geoType = MultiPoint.class;
                break;
            case "LineString":
                geoType = LineString.class;
                break;
            case "MultiLineString":
                geoType = MultiLineString.class;
                break;
            case "Polygon":
                geoType = Polygon.class;
                break;
            case "MultiPolygon":
                geoType = MultiPolygon.class;
                break;
        }
        // 创建shape文件对象
        File file = new File(shpFile);
        Map<String, Serializable> params = new HashMap<String, Serializable>();
        params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
        ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);

        // 设置编码
        Charset charset = Charset.forName(encoding);
        ds.setCharset(charset);

        SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
        //坐标系与投影
        String wkt = CrsUtil.getWKT(wkid);
        tb.setCRS(CRS.parseWKT(wkt));
        //tb.setCRS(DefaultGeographicCRS.WGS84);
        tb.setName("shapefile");

        com.alibaba.fastjson.JSONObject properties = feature0.getJSONObject("properties");
        Map<String, String> map = new HashMap<String, String>();
        int index = 1;
        //构建字段结构
        if (properties != null) {
            Iterator<Entry<String, Object>> iterator = properties.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, Object> entry = iterator.next();
                String key = entry.getKey();
                Object entValue = entry.getValue();
                Class<? extends Object> entType;

                //null
                if (StringUtil.isNullOrEmpty(entValue.toString())) {
                    entType = String.class;
                } else {
                    entType = entValue.getClass();
                }
                //校验是否包含中文
                if (StringUtil.isContainChinese(key)) {
                    String currKey = "ZW" + index;
                    tb.add(currKey, entType);
                    map.put(key, currKey);
                    index++;
                } else {
                    tb.add(key, entType);
                    map.put(key, key);
                }
            }
        }
        tb.add("the_geom", geoType);
        // 定义图形信息和属性信息
        ds.createSchema(tb.buildFeatureType());

        GeometryJSON gjson = new GeometryJSON(10);
        // 设置Writer
        FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
        for (int i = 0, len = features.size(); i < len; i++) {
            // String strFeature = features.get(i).toString();
            com.alibaba.fastjson.JSONObject featureJson = features.getJSONObject(i);
            com.alibaba.fastjson.JSONObject feaGeomObject = featureJson.getJSONObject("geometry");
            com.alibaba.fastjson.JSONObject currProperties = featureJson.getJSONObject("properties");
			/*
			if(feaGeomObject == null || currProperties==null) {
				continue;
			}
			*/

            if (feaGeomObject == null) {
                continue;
            }

            SimpleFeature feature = writer.next();
            //1-属性
            if (currProperties != null) {
                Iterator<Entry<String, Object>> iterator = currProperties.entrySet().iterator();
                while (iterator.hasNext()) {
                    Entry<String, Object> entry = iterator.next();
                    Object val = entry.getValue();
                    if (val != null) {
                        String currKey = map.get(entry.getKey());
                        if (val instanceof String) {
                            if (StringUtil.isContainChinese((String) val)) {
                                feature.setAttribute(currKey, new String(val.toString()));
                            } else {
                                feature.setAttribute(currKey, val);
                            }
                        } else {

                            feature.setAttribute(currKey, val);
                        }
                    }
                }
            }

            //2-几何图形
            if (feaGeomObject != null) {
                String geometry = feaGeomObject.toString();
                Reader reader = new StringReader(geometry);

                feature.setAttribute("the_geom", gjson.read(reader));
                writer.write();
            }

        }

        writer.close();
        ds.dispose();
    }

}